//
//  PostCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/24/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

protocol ContactItemProtocol : class {
    var titleLbl : UILabel { get set }
    var icon: UIImageView { get set }
}

final class Divider: UIView {
    
    init (parent: UIView,
          color: UIColor? = UIColor.greyColor, inset: CGFloat = 0) {
        super.init(frame: .zero)
        self.backgroundColor = color
        parent.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.leading.trailing.equalToSuperview().inset(inset)
            make.top.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("s")
    }
}


final class ContactItem: UIView, ContactItemProtocol {
    var titleLbl: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textColor = .white
        label.textAlignment = .center
        return label
    }()
    
    var icon: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        return img
    }()
    
    init (title: String, image: String) {
        super.init(frame: .zero)
        self.addSubview(titleLbl)
        self.addSubview(icon)
        
        titleLbl.text = title
        icon.image = UIImage(named: image)
        
        titleLbl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-12)
        }
        icon.snp.makeConstraints { (make) in
            make.width.height.equalTo(22)
            make.bottom.equalTo(titleLbl.snp.top).offset(-12)
            make.centerX.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



final class PostCell: UITableViewCell, ConfigurableCell, OptionCellProtocol {

    // MARK: - UI Elements
    
    /// Buildling layout
    lazy private var separatorView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 244/255, green: 246/255, blue: 250/255, alpha: 1)
        return view
    }()
    
    lazy private var topView: UIView = {
        let view = UIView()
        return view
    }()
        /// City name
    lazy private var cityNameLbl: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.text = "Алматы"
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textColor = .greyColor
        return label
    }()
        /// Top Feature Icon
    lazy private var topIcon: UIImageView = {
        let img = UIImageView()
        img.image = UIImage(named: "top")
        img.contentMode = .scaleAspectFit
        return img
    }()
        /// Like Button
    lazy var likeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "like")?.withRenderingMode(.alwaysTemplate),
            for: .normal)
        button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        return button
    }()
        /// Car's images container
    lazy private var imagesScrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentSize = CGSize(width: 1000, height: 84)
        return scrollView
    }()
    
    lazy private var newIcon: UIView = {
        let view = UIView()
        
        let label = UILabel()
        label.text = "Новый"
        label.font = UIFont.systemFont(ofSize: 13)
        label.textAlignment = .center
        label.textColor = .white
        label.tag = 2
        view.backgroundColor = UIColor(red: 87/255, green: 172/255, blue: 87/255, alpha: 1)
        view.addSubview(label)
        return view
    }()
    
        /// Main Details Label
    lazy private var detailsLbl: UILabel = {
        let label = UILabel()
        label.text = "Lorem ipsum sit dolor amet"
        label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        label.numberOfLines = 0
        return label
    }()
        /// Car's price label
    lazy private var priceLbl: UILabel = {
       let label = UILabel()
       label.text = "140000 T"
       label.font = UIFont.systemFont(ofSize: 29, weight: .bold)
       label.numberOfLines = 0
       return label
    }()
        /// Расрочка
    lazy private var rasrochkaView: UIView = {
        let view = UIView ()
        view.backgroundColor = .blueColor
        view.layer.cornerRadius = 10.0
        
        let label = UILabel()
        label.tag = 1
        label.textColor = .white
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textAlignment = .center
        label.text = "Рассрочка 0% на 1 год"
        view.addSubview(label)
        return view
    }()
        /// Post's Footer View
    lazy private var footerView: UIView = {
        let view = UIView()
        return view
    }()
    
    lazy private var dateLbl: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        label.textColor = .greyColor
        label.text = "час назад"
        label.textAlignment = .left
        return label
    }()
    
    lazy private var visCountView: UIStackView = {
        let view = UIStackView()
        view.axis = .horizontal
        view.spacing = 8
        view.alignment = .center
        view.distribution = .equalSpacing
        
        // vis icon
        let icon = UIImageView(frame: CGRect(x: 0, y: 0, width: 16, height: 10.5))
        icon.tag = 1
        icon.image = UIImage(named: "eye")
        
        // vis count label
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 24))
        label.tag = 2
        label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        label.textColor = .greyColor
        label.text = ""
        label.sizeToFit()
        
        view.addArrangedSubview(icon)
        view.addArrangedSubview(label)
        
        icon.snp.makeConstraints { (make) in
            make.width.equalTo(18)
            make.height.equalTo(16)
        }

        return view
    }()
    
    /// Contact buttons
    lazy public var callBtn: ContactItem = {
        let btn = ContactItem(title: "Позвонить", image: "call")
        btn.backgroundColor = UIColor(red: 60/255, green: 72/255, blue: 88/255, alpha: 1)
        return btn
    }()
    
    lazy public var messageBtn: ContactItem = {
        let btn = ContactItem(title: "Написать", image: "message")
        btn.backgroundColor = .darkBlueColor
        return btn
    }()
    
    private var footerTop: Constraint!
    
    // MARK: - Properties
    
    var delegate: OptionCellActionProtocol!
    private var carImages: [UIView] = []
    
    // MARK: Main Model
    
    private var post: PostModel! {
        didSet {
            self.setUpUI()
            
            if (post.isRassrochka) {
                self.addRassrochka()
            } else {
                self.rasrochkaView.removeFromSuperview()
                self.addFooterConstraints(top: priceLbl.snp.bottom)
            }
            
            if (oldValue == nil || oldValue.images != post.images) {
                _ = imagesScrollView.subviews.map {
                    $0.removeFromSuperview()
                }
                
                carImages = []
                self.addScrollItems(images: post.images)
            }
            
            if oldValue == nil || oldValue.postMarketing != post.postMarketing {
                self.setTheme(isDark: post.postMarketing.colored)
            }
        }
    }
    
    // MARK: - Updating UI
    
    func configure(data post: PostModel?, index: Int) {
        self.post = post!
    }
    
    func returnData() -> PostModel? {
        return nil
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
        self.addUIConstraints()
    }
        
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK: - UI

extension PostCell {
    
    private func addViews() {
        self.contentView.addSubview(separatorView)
        self.contentView.addSubview(topView)
        topView.addSubview(cityNameLbl)
        topView.addSubview(topIcon)
        topView.addSubview(likeButton)
        self.contentView.addSubview(imagesScrollView)
        self.contentView.addSubview(detailsLbl)
        self.contentView.addSubview(priceLbl)
        self.contentView.addSubview(rasrochkaView)
        self.contentView.addSubview(footerView)
        let _ = Divider(parent: self.footerView)
        footerView.addSubview(dateLbl)
        footerView.addSubview(visCountView)
    }
    
    private func setUpUI () {
        self.cityNameLbl.text = post.region?.name
        self.likeButton.tintColor = post.isLiked ? .blue : .gray
        self.topIcon.isHidden = !post.isTop
        
        let regularText = [post.model, post.pokolenie, post.serie, post.modification].joined(separator: " ")
        self.detailsLbl.attributedText = self.createDetailsText(strong: post.marka, normal: regularText)
        self.priceLbl.text = post.price
        self.dateLbl.text = post.date
        (self.visCountView.viewWithTag(2) as! UILabel).text = post.visCount
    }
    
    private func setTheme (isDark: Bool) {
        contentView.backgroundColor = isDark ? .darkBlueColor : .white
        priceLbl.textColor = isDark ? .white : .black
        messageBtn.backgroundColor = isDark ? .darkGray : .darkBlueColor
    }
    
    private func createDetailsText (strong: String, normal: String) -> NSMutableAttributedString  {
        let textColor = post.postMarketing.colored ? UIColor.white : .black
        
        let attributedString = NSMutableAttributedString(string: " " + normal, attributes: [NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)])
        
        let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: textColor]
        let boldString = NSMutableAttributedString(string: strong, attributes:attrs)
        
        boldString.append(attributedString)
        return boldString
    }
    
    private func addScrollItems (images: [PostImage]) {
        self.addImages(images: images)
        self.addContactButtons()
        
        if (post.tag != nil) {
            self.addTag(tag: post.tag!)
        }
    }
    
    private func addImages (images: [PostImage]) {
        
        imagesScrollView.contentSize = CGSize(width: CGFloat((post.images.count + 2) * 158) + 24.0, height: 84.0)
        
        for (i, image) in post.images.enumerated() {
            
            let isFirst = carImages.count == 0
            
            let imageView = self.createCarImage(urlString: image.image, isFirst: isFirst, index: i)
            
            self.imagesScrollView.addSubview(imageView)
            
            let leading = isFirst ? imagesScrollView.snp.leading : carImages.last!.snp.trailing
            
            imageView.snp.makeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.leading.equalTo(leading).offset(isFirst ? 16 : 8)
                make.width.equalTo(150)
                make.height.equalTo(84)
            }
            
            carImages.append(imageView)
        }
    }
    
    private func createCarImage (urlString: String, isFirst: Bool, index: Int) -> UIImageView {
        
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.sd_setImage(with: URL(string: urlString), placeholderImage: UIImage(named: "noPhoto"))
        
        if (isFirst) {
            imageView.layer.cornerRadius = 8.0
            imageView.clipsToBounds = true
            imageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
        }
        
        return imageView
    }
    
    private func addContactButtons () {
        for button in [callBtn, messageBtn] {
            let isFirst = carImages == []
            button.clipsToBounds = true
            if (isFirst) {
                button.layer.cornerRadius = 8.0
                button.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
            } else if (button == messageBtn) {
                button.layer.cornerRadius = 15
                button.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]
            }
            self.imagesScrollView.addSubview(button)
            button.snp.makeConstraints { (make) in
                make.height.equalTo(84)
                make.width.equalTo(150)
                make.leading
                    .equalTo(isFirst ? imagesScrollView : carImages.last!.snp.trailing)
                    .offset(isFirst ? 16 : 8)
                make.centerY.equalToSuperview()
            }
            carImages.append(button)
        }
    }
    
    /// Adding new view
    private func addTag (tag: PostModel.Tag) {
        imagesScrollView.addSubview(newIcon)
        newIcon.backgroundColor = tag.color
        (newIcon.viewWithTag(2) as! UILabel).text = tag.text
        
        newIcon.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.leading.equalToSuperview().offset(16)
            make.height.equalTo(24)
            make.width.equalTo(61)
        }
        newIcon.clipsToBounds = true
        newIcon.layer.cornerRadius = 8
        newIcon.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]
        
        imagesScrollView.bringSubviewToFront(newIcon)
        let label = newIcon.subviews[0] as! UILabel
        
        label.snp.makeConstraints { (make) in
            make.centerX.centerY.equalToSuperview()
        }
    }
    
    // MARK: - Constraints
    
    private func addUIConstraints () {
        self.separatorView.snp.makeConstraints { (make) in
            make.height.equalTo(12)
            make.leading.top.trailing.equalToSuperview()
        }
        
        self.topView.snp.makeConstraints { (make) in
            make.height.equalTo(24)
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalTo(separatorView.snp.bottom).offset(16)
        }
        
        self.topIcon.snp.makeConstraints { (make) in
            make.width.equalTo(20)
            make.height.equalTo(18)
            make.centerY.centerX.equalToSuperview()
        }
        
        self.likeButton.snp.makeConstraints { (make) in
            make.width.equalTo(28);
            make.height.equalTo(26);
            make.trailing.centerY.equalToSuperview()
        }
        
        self.cityNameLbl.snp.makeConstraints { (make) in
            make.trailing.equalTo(topIcon.snp.leading)
            make.height.centerY.leading.equalToSuperview()
        }
        self.imagesScrollView.snp.makeConstraints { (make) in
            make.height.equalTo(84)
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(topView.snp.bottom).offset(12)
        }
        self.detailsLbl.snp.makeConstraints { (make) in
            make.top.equalTo(self.imagesScrollView.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        self.priceLbl.snp.makeConstraints { (make) in
            make.top.equalTo(detailsLbl.snp.bottom).offset(12)
            make.leading.equalToSuperview().inset(16)
            make.height.equalTo(40)
        }
        self.rasrochkaView.snp.makeConstraints { (make) in
            make.top.equalTo(priceLbl.snp.bottom).offset(12)
            make.leading.equalToSuperview().inset(16)
            make.width.equalTo(180)
            make.height.equalTo(30)
        }
        (self.rasrochkaView.viewWithTag(1) as! UILabel).snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        
        self.addFooterConstraints(top: rasrochkaView.snp.bottom)
        
        self.dateLbl.snp.makeConstraints { (make) in
            make.centerY.leading.equalToSuperview()
            make.height.equalTo(24)
        }
        self.visCountView.snp.makeConstraints { (make) in
            make.leading.equalTo(dateLbl.snp.trailing).offset(33)
            make.height.equalTo(24)
            make.centerY.equalToSuperview()
        }
    }
    
    private func addRassrochka () {
        self.contentView.addSubview(rasrochkaView)
        self.rasrochkaView.snp.makeConstraints { (make) in
            make.top.equalTo(priceLbl.snp.bottom).offset(12)
            make.leading.equalToSuperview().inset(16)
            make.width.equalTo(180)
            make.height.equalTo(30)
        }
        self.footerTop.deactivate()
        self.footerView.snp.makeConstraints { (make) in
            make.top.equalTo(rasrochkaView.snp.bottom).offset(12)
        }
    }
    
    private func addFooterConstraints (top: ConstraintItem) {
        self.footerView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            self.footerTop = make.top.equalTo(top).offset(12).constraint
            make.height.equalTo(52)
            make.bottom.equalToSuperview()
        }
    }
}
